const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
//获取应用实例
const app = getApp();
var that;
let timer = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    room:{},
    houseNo:'',
    banner: [],
    picIndex: 0,
    isShare:false, //是否来自于分享
    homeownersNo:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    //console.log('rrrrrrrrrrrrrrr',options);
    app.getBaseEnums().then(baseEnums => {
      var ids = baseEnums.deviceLs.map(function (i, n) {
        return i.id;
      });
      that.setData({
        baseEnums: baseEnums,
        roomTypes: baseEnums.roomTypes,
        deviceIds: ids,
      });
    });
    //获取房间编号
    if(options.houseNo){
      that.setData({
        houseNo: options.houseNo,
        homeownersNo: options.homeownersNo,
        unitName: options.unitName,
        coordinates: options.coordinates,
        mobile: options.mobile,
        unitAddress: options.unitAddress,
        isShare: options.isShare?true:false,
      });
      that.initData();
    }else{
      util.toast.fail('参数错误');
    }
  },
  initData(){
    app.postForm(api.QueryRoom, { houseNo: that.data.houseNo, isAllow:true}, {retry:3}).then(rsp => {
      //console.log('rspppppp',rsp);
      if (rsp.data) {
        var i = rsp.data;
        i.imgs = [];
        if (i.photoUrl && i.photoUrl.indexOf('/') != -1) {
          i.imgs = i.photoUrl.split(',').map(function (v, k) {
            return app.showImg(v);
          });
        }
        //房间租金分转元
        i.rentAmount = (i.rentAmount / 100).toFixed(2);
        if (i.rentAmount == parseInt(i.rentAmount)) {
          i.rentAmount = parseInt(i.rentAmount);
        }
        //设备列表
        var deviceList = JSON.parse(i.deviceList);
        deviceList.forEach(function (ii, n) {
          var deviceIndex = that.data.deviceIds.indexOf(ii.id);
          if (deviceIndex != -1) {
            ii.text = that.data.baseEnums.deviceLs[deviceIndex].typeName;
          }
        });
        i.deviceList = deviceList;
        that.setData({
          room: i,
          banner: i.imgs
        });
      }
    }).catch((err) => {
      console.log(err);
    });
  },
  applyCheckIn(){ //申请入住
    var unitName = that.data.unitName;
    var floor = that.data.room.floor;
    var houseName = that.data.room.houseName;
    //检测是否有登录
    if (app.globalData.hasLogin){
      wx.navigateTo({
        url: '/pages/checkin/index?unitName=' + unitName + '&floor=' + floor + '&houseName=' + houseName,
      })
    }else{
      var jumpPage = 'pages/checkin/index?unitName=' + unitName + '&floor=' + floor + '&houseName=' + houseName;
      var p = encodeURIComponent(jumpPage);
      wx.navigateTo({
        url: '/pages/auth/login/login?page=' + p,
      })
    }
  },
  navBack(){
    if (that.data.isShare){
      wx.navigateTo({
        url: '/pages/houseRes/share/list?scene=' + encodeURIComponent(that.data.homeownersNo),
      })
    }else{
      wx.navigateBack({
        delta: 1
      })
    }
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: that.data.banner // 需要预览的图片http链接列表
    })
  },
  callPhone(e) {
    var phoneNumber = that.data.mobile;
    if (phoneNumber) {
      wx.makePhoneCall({
        phoneNumber: phoneNumber,
        fail() { }
      })
    } else {
      util.toast.fail('手机号不存在');
    }
  },
  iCCall() { //一键导航
    let unitCoordinates = that.data.coordinates;
    if (unitCoordinates && unitCoordinates.indexOf(',') == -1) {
      util.toast.fail('经纬度错误');
      return false;
    }
    let latitude = Number(unitCoordinates.split(',')[0]);
    let longitude = Number(unitCoordinates.split(',')[1]);
    let name = that.data.unitAddress;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则地图定位功能将无法使用',
            success: function (res) {
              if (res.cancel) {
                console.info("1授权失败返回数据");
              } else if (res.confirm) {
                //village_LBS(that);
                wx.openSetting({
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 5000
                      })
                      wx.openLocation({
                        latitude: latitude,
                        longitude: longitude,
                        name: name,
                        scale: 28
                      })
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 5000
                      })
                    }
                  }
                })
              }
            }
          })
        } else {
          wx.openLocation({
            latitude: latitude,
            longitude: longitude,
            name: name,
            scale: 28
          })
        }
      }
    })
  },
  picChange(e) {
    that.setData({
      picIndex: e.detail.current
    });
  },
  changeColor() {
    if (timer) clearInterval(timer)
    let that = this
    let colorArr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    timer = setInterval(() => {
      let color_start = '',
        color_end = '',
        color_center = ''
      for (let i = 0; i < 6; i++) {
        color_start += colorArr[Math.floor(Math.random() * 16)]
      }
      for (let i = 0; i < 6; i++) {
        color_center += colorArr[Math.floor(Math.random() * 16)]
      }
      for (let i = 0; i < 6; i++) {
        color_end += colorArr[Math.floor(Math.random() * 16)]
      }
      that.setData({
        color_center,
        color_start,
        color_end,
        rotate: Math.floor(Math.random() * 181)
      })
    }, 700)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    that.changeColor();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if (timer) clearInterval(timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (timer) clearInterval(timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '这里的房间实惠啊,快来看看吧！！！',
      path: '/' + that.route + '?houseNo=' + that.data.room.houseNo + '&coordinates=' + that.data.coordinates + '&mobile=' + that.data.mobile + '&unitAddress=' + that.data.unitAddress + '&homeownersNo=' + that.data.homeownersNo + '&isShare='+true,
      success: function (res) { }
    }
  }
})